package servlet;

import dao.UserDAO;
import pojo.User;
import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends BaseServlet {

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            User user = UserDAO.login(username, password);
            if (user != null) {
                // 登录成功
                sendJsonResponse(response, new ApiResult(200, "登录成功", user));
            } else {
                // 登录失败
                sendJsonResponse(response, new ApiResult(401, "用户名或密码错误", null)); // 401 Unauthorized
            }
        } catch (SQLException e) {
            sendJsonResponse(response, new ApiResult(500, "登录失败", e.getMessage()));
        }
    }
}
